<template>
  <view class="page" :style="{ paddingTop: (statusBarHeight) + 'px' }">
    <!-- 顶部标题栏 -->
    <view class="nav">
      <text class="nav-title">首页</text>
      <view class="nav-actions">
        <text class="icon">···</text>
      </view>
    </view>

    <!-- 顶部轮播 Banner -->
    <swiper class="banner" circular autoplay interval="2000" duration="500" indicator-dots indicator-active-color="#0ea5a5">
      <swiper-item v-for="(img,i) in banners" :key="i">
        <image class="banner-img" :src="img" mode="aspectFill" />
      </swiper-item>
    </swiper>

    <!-- 快捷功能面板 -->
    <view class="panel panel-grid">
      <view class="grid">
        <view class="grid-item" v-for="(g,i) in grids" :key="i" @tap="onGridTap(g)">
          <view class="grid-icon">
            <text class="grid-dot">{{ g.icon }}</text>
          </view>
          <text class="grid-text">{{ g.text }}</text>
        </view>
      </view>
    </view>

    <!-- 公告卡片（按更新时间最近） -->
    <view class="panel panel-announcement">
      <view class="ann-left">
        <text class="ann-mark">最新</text>
        <text class="ann-title">公告</text>
      </view>
      <view class="ann-right">
        <text class="ann-item" v-for="(a,idx) in announcements.slice(0,4)" :key="a.id" @tap="openAnnouncement(a)">{{ a.title }}</text>
      </view>
    </view>

    <!-- 热门活动 -->
    <view class="section">
      <text class="section-title">景区介绍</text>
      <view class="cards">
        <view class="card" v-for="(s,si) in scenics" :key="s.id || si">
          <image class="card-img" :src="s.coverUrl || s.img || s.imageUrl" mode="aspectFill" />
          <!-- #ifdef MP-WEIXIN -->
          <navigator class="card-btn" :url="buildDetailUrl(s)">内容详细</navigator>
          <!-- #endif -->
          <!-- #ifndef MP-WEIXIN -->
          <view class="card-btn" @tap.stop="openScenic(s)" @click.stop="openScenic(s)" @touchend.stop="openScenic(s)">内容详细</view>
          <!-- #endif -->
        </view>
      </view>
    </view>

    <!-- 居中弹窗（uni-popup），跨端兼容更好 -->
    <uni-popup ref="scenicPopup" type="center" @maskClick="closeDetail">
      <view class="modal">
        <view class="modal-title">{{ detailTitle }}</view>
        <view class="modal-content">{{ detailContent }}</view>
      </view>
    </uni-popup>

    <emergency-sos bottom="160" right="24" />
    <custom-tabbar :active="0" @center-tap="onCenterTap" />
  </view>
</template>

<script>
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
import EmergencySOS from '@/components/emergency-sos/emergency-sos.vue'
import { listAnnouncements } from '@/api/announcement'
import { listScenics } from '@/api/scenic'
import config from '@/config'
import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'

export default {
  components: { CustomTabbar, UniPopup, EmergencySOS },
  onShow() { this.fetchLatestAnnouncements() },
  data() {
    return {
      statusBarHeight: 0,
      banners: [
        '/static/project/屏幕截图 2025-10-14 112643.png',
        '/static/project/屏幕截图 2025-10-14 112809.png',
        '/static/project/屏幕截图 2025-10-14 112848.png'
      ],
      grids: [
        { text: '服务范围', icon: '◧', url: '/pages/service/scope' },
        { text: '公告', icon: '◩', url: '/pages/announcement/list' },
        { text: '服务预约', icon: '◓', url: '' },
        { text: '增值服务', icon: '＋', url: '/pages/service/value-added' }
      ],
      scenics: [],
      announcements: [],
      detailTitle: '',
      detailContent: ''
    }
  },
  created() {
    const info = uni.getSystemInfoSync && uni.getSystemInfoSync()
    this.statusBarHeight = (info && info.statusBarHeight) ? info.statusBarHeight : 20
    this.fetchScenics()
  },
  methods: {
    onGridTap(item) {
      if (!item || !item.url) return
      uni.navigateTo({ url: item.url })
    },
    openScenic(item) {
      if (!item) return
      const id = item.id
      if (id) {
        uni.navigateTo({ url: `/pages/scenic/detail?id=${id}` })
        return
      }
      // 无 id 时使用本地标题/内容
      const title = item.name || '内容详细'
      const content = item.description || item.desc || '暂时无内容'
      const cover = item.coverUrl || item.img || item.imageUrl || ''
      const coverParam = cover ? `&coverUrl=${encodeURIComponent(cover)}` : ''
      uni.navigateTo({ url: `/pages/scenic/detail?title=${encodeURIComponent(title)}&content=${encodeURIComponent(content)}${coverParam}` })
    },
    buildDetailUrl(item) {
      if (!item) return ''
      const id = item.id
      if (id) return `/pages/scenic/detail?id=${id}`
      const title = item.name || '内容详细'
      const content = item.description || item.desc || '暂时无内容'
      const cover = item.coverUrl || item.img || item.imageUrl || ''
      const coverParam = cover ? `&coverUrl=${encodeURIComponent(cover)}` : ''
      return `/pages/scenic/detail?title=${encodeURIComponent(title)}&content=${encodeURIComponent(content)}${coverParam}`
    },
    closeDetail() {
      this.$refs.scenicPopup && this.$refs.scenicPopup.close()
      this.detailTitle = ''
      this.detailContent = ''
    },
    onCenterTap() {
      // 中间 AI 咨询 - 已在 tabbar 组件内部处理
      // 此方法保留以便未来扩展
    },
    async fetchScenics() {
      try {
        const res = await listScenics({ status: 'ONLINE' })
        const list = Array.isArray(res.data) ? res.data : (res.rows || res.list || [])
        const base = (config && config.baseUrl) ? String(config.baseUrl).replace(/\/$/, '') : ''
        this.scenics = (list || []).map(it => {
          let cover = it.coverUrl || it.imageUrl || it.img || it.main_photo_url
          if (cover && /^\/[a-zA-Z]/.test(cover)) {
            cover = base + cover
          }
          return {
            id: it.id,
            name: it.name || it.title || '',
            description: it.description || it.desc || '',
            coverUrl: cover
          }
        })
      } catch (e) {
        this.scenics = []
      }
    },
    async fetchLatestAnnouncements() {
      try {
        const res = await listAnnouncements({ status: 'PUBLISHED' })
        const list = Array.isArray(res.data) ? res.data : (res.rows || res.list || [])
        const mapped = (list || []).map(this.mapAnnouncement)
        // 本地按 updatedTime 倒序，取最新
        mapped.sort((a, b) => (b.updatedTime || 0) - (a.updatedTime || 0))
        this.announcements = mapped
      } catch (e) {
        this.announcements = []
      }
    },
    mapAnnouncement(raw) {
      const toTs = (v) => {
        if (!v) return 0
        const d = typeof v === 'number' ? new Date(v) : new Date(String(v).replace(/-/g, '/'))
        return isNaN(d.getTime()) ? 0 : d.getTime()
      }
      return {
        id: raw.id,
        title: raw.title || '',
        updatedTime: toTs(raw.updated_time || raw.updatedTime || raw.publish_time || raw.publishTime)
      }
    },
    openAnnouncement(a) {
      if (!a || !a.id) return
      uni.navigateTo({ url: `/pages/announcement/detail?id=${a.id}` })
    }
  }
}
</script>

<style scoped>
.page {
  padding: 0 24rpx 140rpx 24rpx;
}
.nav {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.nav-title {
  font-size: 36rpx;
  font-weight: 700;
}
.nav-actions .icon {
  font-size: 36rpx;
  color: #111827;
}
.banner {
  width: 100%;
  height: 360rpx;
  border-radius: 16rpx;
  overflow: hidden;
}
.banner-img { width: 100%; height: 100%; }

.panel {
  background: #fff;
  margin-top: 24rpx;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 6rpx 24rpx rgba(0,0,0,0.04);
}
.panel-grid .grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24rpx 12rpx;
}
.grid-item { display: flex; flex-direction: column; align-items: center; }
.grid-icon {
  width: 96rpx; height: 96rpx; border-radius: 48rpx;
  background: #eef6f6; color: #0ea5a5; display: flex; align-items: center; justify-content: center;
}
.grid-dot { font-size: 40rpx; }
.grid-text { margin-top: 12rpx; font-size: 24rpx; color: #444; }

.panel-announcement { display: flex; }
.ann-left { width: 160rpx; background: linear-gradient(180deg,#19c3a1,#0ea5a5); border-radius: 12rpx; color: #fff; display: flex; flex-direction: column; align-items: center; justify-content: center; }
.ann-mark { font-size: 22rpx; opacity: .9; }
.ann-title { font-size: 28rpx; font-weight: 700; margin-top: 6rpx; }
.ann-right { flex: 1; padding: 16rpx 24rpx; display: grid; grid-template-rows: repeat(4, 1fr); row-gap: 6rpx; }
.ann-item { font-size: 24rpx; color: #3f3f46; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

.section { margin-top: 24rpx; }
.section-title { font-size: 28rpx; font-weight: 700; color: #374151; }
.cards { margin-top: 16rpx; display: grid; grid-template-columns: repeat(2, 1fr); gap: 16rpx; }
.card { height: 220rpx; border-radius: 12rpx; overflow: hidden; position: relative; }
.card-img { width: 100%; height: 100%; }
.card-btn { position: absolute; right: 12rpx; bottom: 12rpx; height: 56rpx; line-height: 56rpx; padding: 0 20rpx; font-size: 24rpx; background: rgba(14,165,165,.95); color: #fff; border-radius: 10rpx; z-index: 5; }
.overlay { position: fixed; left: 0; top: 0; right: 0; bottom: 0; background: rgba(0,0,0,.45); display: flex; align-items: center; justify-content: center; z-index: 999; }
.modal { max-width: 80vw; max-height: 70vh; background: #fff; border-radius: 16rpx; padding: 24rpx; box-sizing: border-box; overflow: hidden; }
.modal-title { font-size: 30rpx; font-weight: 700; color: #111827; }
.modal-content { margin-top: 12rpx; color: #374151; font-size: 26rpx; line-height: 1.6; max-height: 54vh; overflow-y: auto; }
</style>
